<template>
	<div class="container">
		<div class="message-detail-header drag">
			<!--      昵称-->
			<div class="nick">{{ friendName }}</div>
		</div>
		<!--    聊天容器-->
		<main ref="mainContent">
			<div class="message-content">
				<!--        每条消息-->
				<div class="message-item" v-for="(item, index) in messageStore.messageChatList" :key="index">
					<!--          消息时间-->
					<div
						class="message-time"
						v-if="index === 0 ? true : messageStore.messageChatList[index - 1].time !== item.time"
					>
						{{ item.time }}
					</div>
					<!--          用户昵称:只在群聊里面出现-->
					<div
						class="user-nick"
						v-if="chatType === 'group' && item.userId._id !== userInfoStore.userInfo._id"
					>
						{{ item.userId.nick }}
					</div>
					<!--          每条消息-->
					<div :class="item.userId._id === userInfoStore.userInfo._id ? 'message-my' : 'message-friend'">
						<!--            对方消息头像在左侧-->
						<div class="user-pic" v-if="item.userId._id !== userInfoStore.userInfo._id">
							<img :src="proxy.$baseUrl + item.userId.imgUrl" />
						</div>
						<!--            已经被删除(红色感叹号)自己-->
						<div
							class="del-dot friend-dot"
							v-if="!item.messageStatus && item.userId._id === userInfoStore.userInfo._id"
						></div>
						<!--            发送的消息-->
						<div class="message-text-wrap">
							<!--              消息类型 0: 文本类型包含emoji表情-->
							<div
								class="message-text"
								:class="item.userId._id == userInfoStore.userInfo._id ? 'my' : 'friend'"
								v-if="item.msgType === 0"
							>
								<div class="message-box" v-html="item.message"></div>
							</div>
							<!--              图片类型 1: 图片类型-->
							<div v-if="item.msgType == 1" class="message-img">
								<div
									style="border-radius: 8px; overflow: hidden"
									:style="
										item.message.indexOf('data:image') > -1
											? ''
											: `height: ${JSON.parse(item.message).height}px;`
									"
								>
									<el-image
										:src="
											item.message.indexOf('data:image') > -1
												? item.message
												: proxy.$baseUrl + JSON.parse(item.message).url
										"
										fit="contain"
										:preview-src-list="[
											item.message.indexOf('data:image') > -1
												? item.message
												: proxy.$baseUrl + JSON.parse(item.message).url
										]"
									>
										<template #placeholder>
											<div
												class="image-slot"
												style="width: 200px; height: 150px; font-size: 15px"
											>
												加载中...
											</div>
										</template>
									</el-image>
								</div>
								<div class="loading" v-if="item.loading">
									<img src="@/assets/svg/loading.svg" />
								</div>
							</div>
							<!--              视频类型 2: 视频类型-->
							<div
								class="message-video-cover"
								v-if="item.msgType == 2"
								@click="handlePreviewVideo(JSON.parse(item.message).url)"
							>
								<div class="video-content">
									<img :src="JSON.parse(item.message).base64" />
									<div class="video-icon">
										<svg
											t="1698152236130"
											class="icon"
											viewBox="0 0 1024 1024"
											version="1.1"
											xmlns="http://www.w3.org/2000/svg"
											p-id="4915"
											width="40"
											height="40"
										>
											<path
												d="M512 1024C229.2224 1024 0 794.7776 0 512S229.2224 0 512 0s512 229.2224 512 512-229.2224 512-512 512z m0-85.3248c235.5968 0 426.5984-191.0272 426.5984-426.6752 0-235.648-191.0016-426.6752-426.5984-426.6752-235.5968 0-426.5984 191.0272-426.5984 426.6752 0 235.648 191.0016 426.6752 426.5984 426.6752z m-127.6928-571.3408c0-9.856 3.072-19.4816 8.8576-27.52a47.7696 47.7696 0 0 1 66.4064-11.008l203.6992 144.6912a47.1552 47.1552 0 0 1 0 77.0304l-203.6992 144.64a47.7952 47.7952 0 0 1-27.6736 8.832 47.4624 47.4624 0 0 1-47.616-47.3344V367.36z"
												fill="#ffffff"
												p-id="4916"
											></path>
										</svg>
									</div>
								</div>
							</div>
							<!--              文件类型 3: 文件类型-->
							<div class="message-file" v-if="item.msgType === 3" @click="handleOpenFile(item.message)">
								<img
									class="file-logo"
									:src="`./file/${supportFileType.includes(JSON.parse(item.message).fileSuffixName) ? JSON.parse(item.message).fileSuffixName : 'other'}.svg`"
									alt=""
								/>
								<!--                文件信息-->
								<div class="message-file-info">
									<div class="file-name">{{ JSON.parse(item.message)?.fileName }}</div>
									<div class="file-size">
										{{ utils.formatFileSize(JSON.parse(item.message).size) }}
									</div>
								</div>
							</div>
						</div>
						<!--            自己的头像在右侧-->
						<div class="user-pic" v-if="item.userId._id === userInfoStore.userInfo._id">
							<img :src="proxy.$baseUrl + item.userId.imgUrl" />
						</div>
					</div>
				</div>
			</div>
		</main>
		<!--    底部消息编辑框-->
		<div class="message-edit-bottom">
			<BottomInput @handleSendMessage="handleSendMessage" />
		</div>
	</div>
</template>
<script setup lang="ts">
import { useMessageStore } from '@/store/modules/message'
import { useUserInfoStore } from '@/store/modules/user'
import { IMessageType } from '@/store/modules/interface/message'
import utils from '@/utils'

const { ipcRenderer, shell } = require('electron')

const { proxy } = getCurrentInstance()
const userInfoStore = useUserInfoStore()
const messageStore = useMessageStore()
const route = useRoute()
const friendName = ref(route.query.name)
// 好友/群聊id
const friendId = ref(route.query.id)
// 群聊还是私聊
const chatType = ref(route.query.type)

// 当前聊天记录页数
const pageNum = ref<number>(1)

const handleSendMessage = (msg: string, msgType: number) => {
	const { _id, nick, imgUrl } = userInfoStore.userInfo
	let data: IMessageType = {
		userId: {
			_id,
			nick,
			imgUrl
		},
		time: utils.formatTime(new Date()),
		msgType,
		message: msg
	}
	// 发送者id
	let uId = _id.toString()
	//接收者id
	let toId = friendId.value + ''
	messageStore.pushMessageData(data)
	// 左侧的消息列表置顶
	messageStore.messageList.map((item, index) => {
		if (item._id === toId) {
			messageStore.messageList.unshift(messageStore.messageList.splice(index, 1)[0])
		}
	})
	// 改变最新的消息状态
	// console.log(messageStore.messageList[0], '12')
	messageStore.messageList[0].lastMsg!.time = new Date()

	if (chatType.value === 'friend') {
		// 私聊消息通知
		proxy.socket.emit('private_chat', data, uId, toId)
	} else {
		console.log('群聊通知')
		// 群聊消息通知
		proxy.socket.emit('group_chat', data, uId, toId)
	}
}

// 获取聊天记录列表
const getChatRecordsList = (pageNum: number = 1) => {
	const userId = userInfoStore.userInfo._id
	if (chatType.value === 'friend') {
		messageStore.getFriendChatRecordsList(userId, friendId.value, pageNum)
	} else {
	}
}

const isShow = ref<boolean>(false)
// 是否初始化
const isInit = ref<boolean>(true)
// 是否加载更多数据
const isLoadingMore = ref<boolean>(false)
// 是加载中
const isLoading = ref<boolean>(false)

// 获取dom
const mainContent = ref()
// 记录内容高度
const mainContentHeightArr = ref<number[]>([])

// 控制滚动方法
const handleScroll = () => {
	// 聊天记录容器高度记录下
	mainContentHeightArr.value.unshift(mainContent.value.scrollHeight)

	if (messageStore.messageChatList.length !== 0 && isInit.value) {
		isShow.value = false
		isInit.value = false
		mainContent.value.scrollTop = mainContent.value.scrollHeight
	} else if (isLoadingMore.value) {
		// 加载更多数据
		mainContent.value.scrollTop = mainContentHeightArr.value[0] - mainContentHeightArr.value[1]
		isLoadingMore.value = false
		isLoading.value = false
	} else {
		mainContent.value.scrollTo({
			top: mainContent.value.scrollHeight,
			behavior: 'smooth'
		})
	}
}

// 路由id改变时
watch(
	() => route.query.id,
	() => {
		// 数据初始化
		isInit.value = true
		mainContentHeightArr.value = []
		pageNum.value = 1
		isLoadingMore.value = false
		isLoading.value = false

		// 加载数据
		friendName.value = route.query.name
		friendId.value = route.query.id
		chatType.value = route.query.type
		const userId = userInfoStore.userInfo._id

		if (chatType.value === 'friend') {
			// 获取与该好友聊天记录
			messageStore.getFriendChatRecordsList(userId, friendId.value, 1)
		} else if (chatType.value === 'group') {
			// 获取群聊聊天记录
			messageStore.getGroupChatRecordsList(userId, friendId.value, 1)
		}
		// 将消息设置为已读 消除未读的提示
		messageStore.setMessageRead()
	}
)

watch(
	() => messageStore.messageChatList,
	() => {
		nextTick(() => {
			if (!messageStore.messageChatList.length) return
			handleScroll()
		})
	},
	{ deep: true }
)

// 看视频
const handlePreviewVideo = (url: string) => {
	ipcRenderer.send('open-video', url)
}

// 支持的文件类型
const supportFileType = [
	'apk',
	'cad',
	'css',
	'dmg',
	'docx',
	'doc',
	'exe',
	'gif',
	'gitignore',
	'html',
	'ipa',
	'iso',
	'java',
	'js',
	'json',
	'jsx',
	'less',
	'md',
	'mp3',
	'mp4',
	'mov',
	'pdf',
	'ppt',
	'psd',
	'py',
	'scss',
	'sql',
	'styles',
	'svg',
	'ts',
	'txt',
	'vue',
	'xlxs',
	'zip'
]

const handleOpenFile = (message: string) => {
	const url = JSON.parse(message).url
	console.log(JSON.parse(message))
	const messageInfo = JSON.parse(message)
	// shell.openExternal(url)
	const aEl = document.createElement('a')
	aEl.setAttribute('download', messageInfo.fileName)
	aEl.setAttribute('href', url)
	aEl.click()
}

onMounted(() => {
	getChatRecordsList()
	messageStore.setMessageRead()
})
</script>

<style scoped lang="scss">
.container {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	position: relative;
	overflow: hidden;
	.message-detail-header {
		width: 100%;
		height: 50px;
		display: flex;
		align-items: center;
		padding-left: 20px;
		font-size: 16px;
		border-bottom: var(--messgae-detail-header-border);
		color: var(--messgae-detail-header-color);

		.nick {
			max-width: 200px;
		}
	}
	main {
		width: 100%;
		flex: 1;
		overflow: auto;
		.message-content {
			width: 100%;
			padding: 15px 20px 0;
			box-sizing: border-box;

			.message-item {
				width: 100%;

				.message-time {
					width: 100%;
					display: flex;
					justify-content: center;
					margin-bottom: 20px;
					font-size: 13px;
					color: #b0b0b0;
				}
				.user-nick {
					font-size: 12px;
					margin-bottom: 8px;
					color: #9a9898;
				}

				.message-my,
				.message-friend {
					width: 100%;
					display: flex;
					margin-bottom: 25px;
					-webkit-user-select: text;
					-moz-user-select: text;
					-ms-user-select: text;
					user-select: text;

					.user-pic {
						width: 40px;
						height: 40px;
						border-radius: 50%;
						overflow: hidden;
						img {
							width: 100%;
							height: 100%;
						}
					}

					.del-dot {
						width: 20px;
						height: 20px;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #ffffff;
						background-color: #ff3300;
						font-size: 13px;
						font-weight: 600;
					}
					.message-text-wrap {
						margin: 0 10px;

						.message-text {
							max-width: 55vw;
							padding: 10px;
							border-radius: 10px;
							line-height: 22px;
							font-size: 15px;
							.message-box {
								width: 100%;
								word-break: break-word;
							}
						}
						.message-img {
							max-width: 200px;
							position: relative;

							.image-slot {
								display: flex;
								justify-content: center;
								align-items: center;
								background: var(--el-fill-color-darker);
								color: var(--el-text-color-secondary);
								font-size: 25px;
							}
						}
						.message-video-cover {
							width: 260px;
							height: 160px;
							position: relative;

							.video-content {
								width: 100%;
								height: 100%;
								border-radius: 10px;
								overflow: hidden;
								background-color: var(--message-video-content-bg-color);
								cursor: pointer;

								img {
									width: 100%;
									height: 100%;
								}

								.video-icon {
									position: absolute;
									top: 50%;
									left: 50%;
									transform: translate(-50%, -50%);
								}
							}

							.progress {
								width: 240px;
								position: absolute;
								left: 10px;
								right: 10px;
								bottom: 7.5px;
							}
						}
						.message-file {
							width: 260px;
							height: 70px;
							background-color: var(--message-file-bg-color);
							color: var(--message-file-color);
							border-radius: 10px;
							padding: 10px;
							display: flex;
							align-items: center;
							cursor: pointer;
							img {
								width: 40px;
								height: 40px;
							}
							.message-file-info {
								display: flex;
								flex-direction: column;
								margin-left: 10px;
								.file-name {
									font-size: 15.5px;
									width: 110px;
									height: 16px;
									line-height: 16px;
									white-space: nowrap;
									overflow: hidden;
									text-overflow: ellipsis;
								}
								.file-size {
									font-size: 12px;
									color: #8c8c8c;
								}
							}
						}
						.friend {
							background-color: var(--message-friend-bg-color);
							color: var(--message-friend-color);
						}
						.my {
							background-color: var(--message-my-bg-color);
							color: var(--message-my-color);
						}
					}
				}

				.message-my {
					justify-content: flex-end;
				}
			}
		}
	}
	.message-edit-bottom {
		width: 100%;
		height: 200px;
		border-top: var(--message-bottom-input-border-top);
		padding: 10px 15px;
	}
}
</style>
